package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.meily.constant.SystemConstants;
import cn.openea.perpartner.meily.constant.enums.ExpressCompany;
import cn.openea.perpartner.meily.constant.enums.NotifySceneEnum;
import cn.openea.perpartner.meily.constant.enums.NotifySendEnum;
import cn.openea.perpartner.meily.thirdparty.BpmSystemApi;
import cn.openea.perpartner.meily.thirdparty.notify.NotifySendEvent;
import cn.openea.perpartner.meily.web.entity.Goods;
import cn.openea.perpartner.meily.web.entity.PersonalInfo;
import cn.openea.perpartner.meily.web.entity.dto.MaterialDownloadDTO;
import cn.openea.perpartner.meily.web.entity.dto.TrialEvaluationDTO;
import cn.openea.perpartner.meily.web.entity.dto.TrialEvaluationSubDTO;
import cn.openea.perpartner.meily.web.entity.vo.GoodsDeliveryNoticeVo;
import cn.openea.perpartner.meily.web.entity.vo.ProductDeliveryVo;
import cn.openea.perpartner.meily.web.service.IGoodsService;
import cn.openea.perpartner.meily.web.service.IPersonalInfoService;
import cn.openea.perpartner.meily.web.service.ITrialEvaluationService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author rains
 * @since 2023-03-09 15:13
 */
@Slf4j
@Service("trialEvaluationService")
public class TrialEvaluationServiceImpl implements ITrialEvaluationService {

    @Autowired
    private IGoodsService goodsService;
    @Resource
    private ApplicationContext applicationContext;
    @Autowired
    private IPersonalInfoService personalInfoService;
    @Resource
    private BpmSystemApi bpmSystemApi;
    @Resource
    private SystemConstants systemConstants;

    /**
     * 获取测评笔记-小程序
     *
     * @param object 用户id、是否要显示商品链接、分页信息等
     * @return
     */
    @Override
    public List<JSONObject> getEvaluationNotesList(JSONObject object) {
        /**
         * 第1步 获取BPM的测评子任务数据
         */
        HashMap<String, Object> params = new HashMap<>();
        // 要查询的用户id
        params.put("queryUserId", object.getString("queryUserId"));
        // 页数
        params.put("pageNum", object.getString("pageNum"));
        // 每页显示的记录
        params.put("pageSize", object.getString("pageSize"));
        JSONObject resObject = bpmSystemApi.sendHttp(params, systemConstants.getEvaluationSubData());
        if (!"200".equals(resObject.getString("code"))) {
            log.error("获取BPM的测评子任务数据失败！");
            return null;
        }
        // JSONArray 转 list
        String js = JSONObject.toJSONString(resObject.getJSONArray("data"), SerializerFeature.WriteClassName);
        List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);
        /**
         * 第2步 遍历测评子任务数据，组装个人资料、商品信息
         */
        for (JSONObject obj : list) {

            // 获取个人资料
            PersonalInfo personalInfo = personalInfoService.getPersonalInfoByUserId(obj.getString("UserId"));

            String Category = "";
            if (StrUtil.isNotBlank(personalInfo.getMainCategory())) {
                Category += personalInfo.getMainCategory();
            }
            if (StrUtil.isNotBlank(Category) && StrUtil.isNotBlank(personalInfo.getSecondCategory())) {
                Category += personalInfo.getSecondCategory();
            }

            obj.put("userId", personalInfo.getUserId());
            obj.put("userName", personalInfo.getUserName());
            obj.put("sex", personalInfo.getSex());
            obj.put("avatarUrl", personalInfo.getAvatarUrl());
            obj.put("identityJob", personalInfo.getIdentityJob());
            obj.put("category", Category);

            // 需要显示商品链接，才需要组装商品信息
            if (object.getBoolean("showGoodsLinks")) {
                LambdaQueryWrapper<Goods> wrapper = new LambdaQueryWrapper<Goods>();
                wrapper.eq(Goods::getGoodsNo, obj.getString("goodsNo"));
                Goods goods = goodsService.getOne(wrapper);

                if (BeanUtil.isNotEmpty(goods)) {
                    obj.put("goodsName", goods.getGoodsName());// 商品名称
                    obj.put("discountPrice", goods.getDiscountPrice());// 商品折扣价

                    // 商品图，只取一张
                    String goodsImages = goods.getGoodsImages();
                    if (StrUtil.isNotBlank(goodsImages)) {
                        obj.put("goodsImages", goodsImages.split(",")[0]);
                    } else {
                        obj.put("goodsImages", "");
                    }

                    // 关联商品点击跳转地址
                    obj.put("url", "/pages_private_scene2/GroupPurchase/DistributionGoods?goodsNo=" + goods.getGoodsNo() + "&goodsId=" + goods.getGoodsId());
                }

            }
        }

        return list;
    }

    /**
     * 获取测评数据列表
     *
     * @param object 包含查询条件
     * @return
     */
    @Override
    public JSONObject getTrialEvaluationDataList(JSONObject object) {

        HashMap<String, Object> params = new HashMap<>();
        // 页数
        params.put("pageNum", object.getString("pageNum"));
        // 每页显示的记录
        params.put("pageSize", object.getString("pageSize"));
        // 搜索内容
        params.put("searchStr", object.getString("searchStr"));
        JSONObject resObject = bpmSystemApi.sendHttp(params, systemConstants.getEvaluationDataList());
        if (!"200".equals(resObject.getString("code"))) {
            log.error("获取测评数据列表失败！");
            return null;
        }

        // 记录总数
        int total = resObject.getInteger("total");

        // JSONArray 转 list
        String js = JSONObject.toJSONString(resObject.getJSONArray("data"), SerializerFeature.WriteClassName);
        List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

        // 返回结果
        JSONObject obj = new JSONObject();
        obj.put("code", 200);
        obj.put("total", total);
        obj.put("rows", list);

        return obj;
    }

    /**
     * 获取测评报名记录列表
     *
     * @param object 包含查询条件
     * @return
     */
    @Override
    public JSONObject getJoinList(JSONObject object) {

        HashMap<String, Object> params = new HashMap<>();
        params.put("pageNum", object.getString("pageNum"));// 页数
        params.put("pageSize", object.getString("pageSize"));// 每页显示的记录
        params.put("id", object.getString("id"));// 测评主文档id
        params.put("partnerId", object.getString("partnerId"));
        params.put("consigneeName", object.getString("consigneeName"));
        params.put("joinStatus", object.getString("joinStatus"));
        params.put("orderStatus", object.getString("orderStatus"));
        params.put("consigneePhoneNum", object.getString("consigneePhoneNum"));
        JSONObject resObject = bpmSystemApi.sendHttp(params, systemConstants.getEvaluationJoinList());
        if (!"200".equals(resObject.getString("code"))) {
            log.error("获取测评报名记录列表失败！");
            return null;
        }

        // 记录总数
        int total = resObject.getInteger("total");

        // JSONArray 转 list
        String js = JSONObject.toJSONString(resObject.getJSONArray("data"), SerializerFeature.WriteClassName);
        List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);

        // 返回结果
        JSONObject obj = new JSONObject();
        obj.put("code", 200);
        obj.put("total", total);
        obj.put("rows", list);

        return obj;
    }

    @Override
    public MaterialDownloadDTO getMaterialDirectory(String code) {
        HashMap<String, Object> params = new HashMap<>();
        // 工单号
        params.put("taskNumber", code);
        JSONObject resObject = bpmSystemApi.sendHttp(params, systemConstants.getEvaluationMaterialDownloadPath());
        if (!"200".equals(resObject.getString("code"))) {
            throw new ServiceException("根据工单号获取测评素材下载路径失败！");
        }
        JSONObject data = resObject.getJSONObject("data");
        return JSON.parseObject(data.toJSONString(), MaterialDownloadDTO.class);
    }

    @Override
    public void productDelivery(ProductDeliveryVo vo) {
        ExpressCompany expressCompany = vo.getExpressCompany();
        if (expressCompany == null) {
            throw new ServiceException("不支持此快递公司");
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("docUnid", vo.getDocUnid());
        params.put("courierName", expressCompany.getName());
        params.put("expressCompanyCode", expressCompany.getCode());
        params.put("courierNumber", vo.getCourierNumber());
        params.put("orderStatus", vo.getOrderStatus());
        JSONObject resObject = bpmSystemApi.sendHttp(params, systemConstants.getSendOutGoods());
        if (!"200".equals(resObject.getString("code"))) {
            log.error("trialEvaluationServiceImpl product delivery method error");
            throw new ServiceException(resObject.getString("msg"));
        }
        Map<String, Object> notifyData = new HashMap<>();
        notifyData.put(NotifySendEnum.SMS.name(), GoodsDeliveryNoticeVo.builder()
                .sendTo(vo.getConsigneeName())
                .phoneNumber(vo.getConsigneePhoneNum())
                .commodity(vo.getSubjectName())
                .company(expressCompany.getName())
                .numbers(vo.getCourierNumber())
                .build());
        try {
            applicationContext.publishEvent(new NotifySendEvent(this,
                    NotifySendEnum.SMS,
                    NotifySceneEnum.GOODS_DELIVERY,
                    notifyData));
        } catch (Exception e) {

        }
    }

    @Override
    public TrialEvaluationSubDTO getEvaluationSubDetailById(String evaluationSubId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("docUnid", evaluationSubId);
        JSONObject resObject = bpmSystemApi.sendHttp(params, systemConstants.getEvaluationSubDetail());
        if (!"200".equals(resObject.getString("code"))) {
            log.error("trialEvaluationServiceImpl getEvaluationSubDetailById method error");
            throw new ServiceException(resObject.getString("msg"));
        }
        String data = resObject.getString("data");
        if (StringUtils.isBlank(data)) {
            return null;
        }
        TrialEvaluationSubDTO evaluationSubDTO = JSON.parseObject(data, TrialEvaluationSubDTO.class);
        JSONObject jsonObject = resObject.getJSONObject("data");
        evaluationSubDTO.setDocCreatedTime(jsonObject.getString("WF_DocCreated"));
        evaluationSubDTO.setTaskNumber(jsonObject.getString("TaskNumber"));
        evaluationSubDTO.setSubject(jsonObject.getString("Subject"));
        return evaluationSubDTO;
    }

    @Override
    public JSONObject getEvaluationTaskList(JSONObject object) {
        HashMap<String, Object> params = new HashMap<>(8);
        // 页数
        params.put("pageNum", object.getString("pageNum"));
        // 每页显示的记录
        params.put("pageSize", object.getString("pageSize"));
        // 搜索内容
        params.put("searchStr", object.getString("searchStr"));
        return bpmSystemApi.sendHttp(params, systemConstants.getEvaluationTaskList());
    }

    @Override
    public void updateEvaluationTask(JSONObject object) {
        HashMap<String, Object> params = new HashMap<>(8);
        // 页数
        params.put("id", object.getString("id"));
        // 每页显示的记录
        params.put("endTime", object.getString("endTime"));
        // 搜索内容
        params.put("limitDays", object.getString("limitDays"));
        JSONObject resObject = bpmSystemApi.sendHttp(params, systemConstants.getUpdateEvaluationTask());
        if (!"200".equals(resObject.getString("code"))) {
            throw new ServiceException(resObject.getString("msg"));
        }
    }
}
